package com.youlv.yl.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.youlv.yl.config.SystemConfig;

import java.io.ByteArrayInputStream;
import java.util.Date;

/**
 * @author Feri
 * @date 2021/12/28 16:30
 * @description:TODO 阿里云-对象存储-OSS
 */
public class AliOssUtils {
    /**
     * yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
     */

    static String endpoint = "oss-cn-shanghai.aliyuncs.com";
    // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
    static String accessKeyId = SystemConfig.ALI_OSS_KEY;
    static String accessKeySecret = SystemConfig.ALI_OSS_SEC;
    public static String bucket = "heyue666";

    // 创建OSSClient实例。
    public static OSS ossClient;

    static {
        ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 实现资源上传，并获取访问路径
     */
    public static String upload(String obj, byte[] data, Date date) {
        //1.实现资源上传
        ossClient.putObject(bucket, obj, new ByteArrayInputStream(data));
        //2.生成访问路径
        return ossClient.generatePresignedUrl(bucket, obj, date).toString();
    }

    /**
     * 实现资源的删除
     */
    public static boolean delete(String obj) {
        try {
            ossClient.deleteObject(bucket, obj);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 验证资源是否存在
     */
    public static boolean exists(String obj) {
        return ossClient.doesObjectExist(bucket, obj);
    }

    /**
     * 创建对象的访问链接
     */
    public static String createUrl(String obj, Date date) {
        return ossClient.generatePresignedUrl(bucket, obj, date).toString();
    }
}